package com.mitgroup.dmrvs.view;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.mitgroup.dmrvs.R;
import com.mitgroup.dmrvs.utils.AppManager;
import com.mitgroup.dmrvs.utils.Utils;
import com.mitgroup.dmrvs.webservice.WSClient;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.PreferencesUtils;

public class OperatorManageActivity extends AppCompatActivity {
    private static final int MSG_LOAD = 1;
    private static final String BUNDLE_LOAD_FAIL ="load_fail";
    private static final String BUNDLE_LOAD_SUCCESS = "load_success";
    private static final String BUNDLE_OPERATOR_LOAD_SUCCESS = "operator_load_success";
    private static final String BUNDLE_LOCAL_ERROR = "local_error";

    private static final int MSG_OPERATOR_DEL = 3;
    private static final String BUNDLE_MSG_OPERATOR_DEL_FAIL ="operator_del_fail";
    private static final String BUNDLE_MSG_OPERATOR_DEL_SUCCESS = "operator_del_success";
    private static final String BUNDLE_MSG_OPERATOR_DEL_JUMP = "operator_del_jump";
    private Intent intent;
    public List<PullUserInfoBean> data = new ArrayList<PullUserInfoBean>();
    List<PullUserInfoBean> list = new ArrayList<PullUserInfoBean>();
    MyAdapter adapter;
    public String userId;
    private ProgressDialog progressDialog;
    @BindView(R.id.btn_back)
    public Button back;
    @OnClick(R.id.btn_back)
    public void onBack(View view) {
        this.finish();
    }
    @BindView(R.id.tv_user_name)
    public TextView tvUserName;
    @BindView(R.id.iv_quit)
    public Button quit;
    @OnClick(R.id.iv_quit)
    public void onQuit(View view) {
        Utils.Exit(this);
    }

    @BindView(R.id.btn_nav01)
    public Button btnReceiveCar;
    @OnClick(R.id.btn_nav01)
    public void onReceiveCar(View view) {
        intent = new Intent(OperatorManageActivity.this,
                ReceiveCarActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.btn_nav02)
    public Button btnDiagnose;
    @OnClick(R.id.btn_nav02)
    public void onDiagnose(View view) {
        intent = new Intent(OperatorManageActivity.this,
                CarDiagnoseActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.btn_nav03)
    public Button btnSettings;
//    @OnClick(R.id.btn_nav03)
//    public void onOperatorManager(View view) {
//        intent = new Intent(OperatorManageActivity.this,
//                OperatorManageActivity.class);
//        startActivity(intent);
//    }

    @BindView(R.id.btn_add_operator)
    public Button btnAddOperator;
    @OnClick(R.id.btn_add_operator)
    public void onAddOperator(View view) {
        intent = new Intent(OperatorManageActivity.this,
                AddOperatorActivity.class);
        intent.putExtra("flag", "1");
        startActivity(intent);
    }
    @BindView(R.id.lv_operator_info)
    public PullToRefreshListView pullToRefresh;
    public int page=0;
    public int firstRow=1;
    public int lastRow=5;
    public int totalRow=0;
    public int totalPage=0;
    public int step=5;
    List<PullUserInfoBean> list1 = new ArrayList<PullUserInfoBean>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_operator_manage);
        ButterKnife.bind(this);
        initView();
    }
    private void initView() {
        AppManager.getAppManager().addActivity(this);
         userId = PreferencesUtils.getString(OperatorManageActivity.this, "userId");
        btnSettings.setBackgroundResource(R.drawable.nav_icon03_active);
        String userName = PreferencesUtils.getString(OperatorManageActivity.this, "userName");
        tvUserName.setText(userName);

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }
    private void initListView()
    {
        ILoadingLayout startLabels = pullToRefresh
                .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("正在载入...");// 刷新时
        startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示
        ILoadingLayout endLabels = pullToRefresh.getLoadingLayoutProxy(
                false, true);
        endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("正在载入...");// 刷新时
        endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示
        // 设置下拉刷新文本
//        pullToRefresh.getLoadingLayoutProxy(false, true)
//                .setPullLabel("上拉刷新...");
//        pullToRefresh.getLoadingLayoutProxy(false, true).setReleaseLabel(
//                "放开刷新...");
//        pullToRefresh.getLoadingLayoutProxy(false, true).setRefreshingLabel(
//                "正在加载...");
        // 设置上拉刷新文本
//        			pullToRefresh.getLoadingLayoutProxy(true, false)
//        					.setPullLabel("下拉刷新...");
//        			pullToRefresh.getLoadingLayoutProxy(true, false).setReleaseLabel(
//        					"放开刷新...");
//        			pullToRefresh.getLoadingLayoutProxy(true, false).setRefreshingLabel(
//        					"正在加载...");
    }
    @Override
    protected void onResume() {
        super.onResume();
        list.clear();
        initListView();
        getUserInfo(userId,firstRow,lastRow);
        pullToRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>(){

            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                new FinishRefresh().execute();
                if(totalRow!=0) {
                   adapter.notifyDataSetChanged();
                }

            }
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                if(totalRow!=0) {
                page+=1;
                firstRow=lastRow+1;
                if(page!=totalPage && page<totalPage)
                {
                    lastRow+=step;
                }
                else
                {
                    if(page>totalPage)
                    {
                        Toast.makeText(OperatorManageActivity.this,"已到最后！", Toast.LENGTH_SHORT).show();
                        Bundle bundle = new Bundle();
                        Message msg;
                        bundle.putString(BUNDLE_LOAD_SUCCESS, "加载成功！");
                        msg = myHandler.obtainMessage();
                        msg.what = MSG_LOAD;
                        msg.setData(bundle);
                        myHandler.sendMessage(msg);
                        return;
                    }
                    else
                    {
                        lastRow=firstRow+totalRow%step;
                    }
                }
                if(page!=0) {
                    final String[] key = {"relUserId", "firstRow", "lastRow"};
                    final String[] value = {userId, firstRow + "", lastRow + ""};
                    progressDialog = ProgressDialog.show(OperatorManageActivity.this,
                            getResources().getString(R.string.notice), "正在加载中...");
                    new Thread(new Runnable() {
                        Bundle bundle = new Bundle();
                        Message msg;

                        @Override
                        public void run() {
                            String rs = "";
                            try {

                                rs = WSClient.soapGetInfo("getUserInfoByRelUserId", key, value);
                                if (rs != null && !"".equals(rs)) {
                                    JSONTokener jsonTokener = new JSONTokener(rs);
                                    JSONObject jsonObject = (JSONObject) jsonTokener
                                            .nextValue();
                                    String status = jsonObject.getString("status");

                                    String content = jsonObject.get("content").toString();

                                    if ("1".equals(status)) {
                                        JSONArray jsonArray = new JSONArray(content);
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject infoJson = jsonArray.getJSONObject(i);
                                            PullUserInfoBean bean = new PullUserInfoBean();
                                            bean.setUser_id(infoJson.getInt("userId"));
                                            bean.setUser_name(infoJson.getString("userName"));
                                            bean.setPassword(infoJson.getString("password"));
                                            bean.setProvince(infoJson.getString("province"));
                                            bean.setReal_name(infoJson.getString("realName"));
                                            bean.setRegister_time(infoJson.getString("registerTime"));
                                            list1.add(bean);
                                        }

                                        bundle.putString(BUNDLE_LOAD_SUCCESS, "加载成功！");
                                    } else {
                                        bundle.putString(BUNDLE_LOAD_FAIL, "无数据加载！");
                                    }
                                } else {
                                    bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                                }
                            } catch (Exception e) {
                                bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                            }
                            msg = myHandler.obtainMessage();
                            msg.what = MSG_LOAD;
                            msg.setData(bundle);
                            myHandler.sendMessage(msg);

                        }
                    }).start();
                 }

                }
                else
                {
                    Toast.makeText(OperatorManageActivity.this,"加载成功！", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
    private void getUserInfo(String userId,int firstRow,int lastRow){
        final String []key={"relUserId","firstRow","lastRow"};
        final String []value={userId,firstRow+"",lastRow+""};
        progressDialog = ProgressDialog.show(OperatorManageActivity.this,
                getResources().getString(R.string.notice), "正在加载中...");
        new Thread(new Runnable() {
            Bundle bundle = new Bundle();
            Message msg;
            @Override
            public void run() {
                String rs = "";
                try {
                    rs = WSClient.soapGetInfo("getUserInfoByRelUserId",key,value);
                    if(rs!=null &&!"".equals(rs))
                    {
                        JSONTokener jsonTokener = new JSONTokener(rs);
                        JSONObject jsonObject = (JSONObject) jsonTokener
                                .nextValue();
                        String status = jsonObject.getString("status");
                        totalRow = Integer.parseInt(jsonObject.getString("total"));
                        totalPage=totalRow/step;
                        if(totalRow%step!=0)
                        {
                            totalPage+=1;
                        }
                        String content = jsonObject.get("content").toString();
                        if("1".equals(status))
                        {
                            JSONArray jsonArray = new JSONArray(content);
                            page=1;
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject infoJson = jsonArray.getJSONObject(i);
                                PullUserInfoBean bean = new PullUserInfoBean();
                                bean.setUser_id(infoJson.getInt("userId"));
                                bean.setUser_name(infoJson.getString("userName"));
                                bean.setPassword(infoJson.getString("password"));
                                bean.setProvince(infoJson.getString("province"));
                                bean.setReal_name(infoJson.getString("realName"));
                                bean.setRegister_time(infoJson.getString("registerTime"));
                                list.add(bean);
                            }

                            bundle.putString(BUNDLE_OPERATOR_LOAD_SUCCESS, "加载成功！");
                        }
                        else
                        {
                            bundle.putString(BUNDLE_LOAD_FAIL, "无数据加载！");
                        }
                    }
                    else
                    {
                        bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                    }
                }
                catch (Exception e) {
                    bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                }
                msg = myHandler.obtainMessage();
                msg.what = MSG_LOAD;
                msg.setData(bundle);
                myHandler.sendMessage(msg);

            }
        }).start();

    }
    private Handler myHandler = new Handler() {
        String key="";
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD:
                    String key1 = msg.getData().keySet().iterator().next();
                    if (BUNDLE_LOAD_FAIL.equals(key1)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(OperatorManageActivity.this,msg.getData().getString(BUNDLE_LOAD_FAIL), Toast.LENGTH_SHORT).show();
                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key1)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }

                        Toast.makeText(OperatorManageActivity.this,"服务器连接失败！", Toast.LENGTH_SHORT).show();
                    }
                    else if (BUNDLE_OPERATOR_LOAD_SUCCESS.equals(key1)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        data=list;
                        adapter = new MyAdapter(OperatorManageActivity.this,data);
                        pullToRefresh.setAdapter(adapter);
                        pullToRefresh.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    else if (BUNDLE_LOAD_SUCCESS.equals(key1)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        if(page>1)
                        {
                            if(list1!=null)
                            {
                                if(list1.size()!=0)
                                {
                                    for(int i=0;i<list1.size();i++)
                                    {
                                        adapter.addLast((PullUserInfoBean)list1.get(i));
                                        new FinishRefresh().execute();
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                                else
                                {
                                    new FinishRefresh().execute();
                                    adapter.notifyDataSetChanged();
                                }

                            }
                            else
                            {
                                new FinishRefresh().execute();
                                adapter.notifyDataSetChanged();
                            }
                            list1.clear();
                        }
                    }
                    break;
                case MSG_OPERATOR_DEL:
                    key = msg.getData().keySet().iterator().next();
                    if (BUNDLE_MSG_OPERATOR_DEL_FAIL.equals(key)) {
                        Toast.makeText(OperatorManageActivity.this,msg.getData().getString(BUNDLE_MSG_OPERATOR_DEL_FAIL), Toast.LENGTH_SHORT).show();
                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key)) {
                        Toast.makeText(OperatorManageActivity.this,"服务器连接失败！", Toast.LENGTH_SHORT).show();
                    }
                    else if (BUNDLE_MSG_OPERATOR_DEL_SUCCESS.equals(key)) {
                        Toast.makeText(OperatorManageActivity.this,msg.getData().getString(BUNDLE_MSG_OPERATOR_DEL_SUCCESS), Toast.LENGTH_SHORT).show();
                        OperatorManageActivity.this.finish();
                        Intent intent = new Intent(OperatorManageActivity.this,
                                OperatorManageActivity.class);
                        startActivity(intent);
                    }
                    break;

                default:
                    break;
            }
            removeMessages(msg.what);

        }
    };
    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result){
//        	      	adapter.notifyDataSetChanged();
            pullToRefresh.onRefreshComplete();
        }
    }
    private class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        ViewHolder viewHolder = null;
        public MyAdapter(Context context, List<PullUserInfoBean> list) {
            Utils.initImageLoader(context);
            mInflater = LayoutInflater.from(context);
            data=list;
        }
        public void addFirst(PullUserInfoBean bean){
            data.add(0, bean);
        }
        public void addLast(PullUserInfoBean bean){
            data.add(bean);
        }
        @Override
        public int getCount() {
            return data.size();
        }
        @Override
        public Object getItem(int position) {
            return data.get(position);
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        public void removeItem(int position) {
            data.remove(position);
            this.notifyDataSetChanged();
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //String url="";
            if(convertView == null){
                viewHolder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.content_list_item_user_info, null);
                viewHolder.userId = (TextView) convertView.findViewById(R.id.tv_user_id);
                viewHolder.userName = (TextView) convertView.findViewById(R.id.tv_user_name1);
                viewHolder.password = (TextView) convertView.findViewById(R.id.tv_password1);
                viewHolder.realName = (TextView) convertView.findViewById(R.id.tv_real_name1);
                viewHolder.province = (TextView) convertView.findViewById(R.id.tv_province1);
                viewHolder.registerTime = (TextView) convertView.findViewById(R.id.tv_register_time1);
                viewHolder.operatorUpdate=(Button) convertView.findViewById(R.id.btn_operator_update);
                viewHolder.operatorDel=(Button) convertView.findViewById(R.id.btn_operator_del);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) convertView.getTag();        				}

            int userId=data.get(position).getUser_id();
            viewHolder.userId.setText(userId+"");
            String userName=data.get(position).getUser_name();
            viewHolder.userName.setText(userName);
            String password=data.get(position).getPassword();
            viewHolder.password.setText(password);
            String realName=data.get(position).getReal_name();
            viewHolder.realName.setText(realName);
            String province=data.get(position).getProvince();
            viewHolder.province.setText(province);
            String registerTime=data.get(position).getRegister_time();
            viewHolder.registerTime.setText(registerTime);

            if(convertView!=null)
            {
                viewHolder.operatorDel.setOnClickListener(new lvButtonListener(position,userId));
                viewHolder.operatorUpdate.setOnClickListener(new lvButtonListener(position,userId,userName,password,realName,province));
            }
            return convertView;
        }

        class ViewHolder{
            TextView userId;
            TextView userName;
            TextView password;
            TextView realName;
            TextView province;
            TextView registerTime;
            Button  operatorDel;
            Button operatorUpdate;
        }
        class lvButtonListener implements View.OnClickListener {
            private int position;
            private int myUserId;
            private String myUserName;
            private String myPassword;
            private String myProvince;
            private String myRealName;
            private String myRegisterTime;
            lvButtonListener(int pos,int userId) {
                position = pos;
                myUserId=userId;
            }
            lvButtonListener(int pos,int userId,String userName, String password,String realName,String province)
            {
                position = pos;
                myUserId=userId;
                myUserName=userName;
                myPassword=password;
                myProvince=province;
                myRealName=realName;
            }
            @Override
            public void onClick(View v) {

                int vid=v.getId();
                if (vid == viewHolder.operatorUpdate.getId())
                {
                    Intent intent = new Intent(OperatorManageActivity.this,
                            AddOperatorActivity.class);
                    intent.putExtra("operatorId", myUserId);
                    intent.putExtra("userName", myUserName);
                    intent.putExtra("password", myPassword);
                    intent.putExtra("realName", myRealName);
                    intent.putExtra("province", myProvince);
                    intent.putExtra("flag", "2");
                    startActivity(intent);
                }
                else if (vid == viewHolder.operatorDel.getId())
                {
                    new AlertDialog.Builder(OperatorManageActivity.this).setTitle("确认删除吗？")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    final String []key1={"userId"};
                                    final String []value1={myUserId+""};

                                    new Thread(new Runnable() {
                                        Bundle bundle = new Bundle();
                                        Message msg;
                                        @Override
                                        public void run() {
                                            try {
                                                String rs = WSClient.soapGetInfo("updateUserInfoIsEnable",key1,value1);

                                                JSONTokener jsonTokener = new JSONTokener(rs);
                                                JSONObject jsonObject = (JSONObject) jsonTokener
                                                        .nextValue();
                                                String status = jsonObject.getString("status");
                                                String content = jsonObject.get("content").toString();

                                                if("1".equals(status))
                                                {
                                                    bundle.putString(BUNDLE_MSG_OPERATOR_DEL_SUCCESS, "删除成功！");
                                                    //removeItem(position);
                                                }
                                                else
                                                {
                                                    bundle.putString(BUNDLE_MSG_OPERATOR_DEL_FAIL, content);
                                                }
                                            }
                                            catch (Exception e) {
                                                bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败，请重试！");
                                            }
                                            msg = myHandler.obtainMessage();
                                            msg.what = MSG_OPERATOR_DEL;
                                            msg.setData(bundle);
                                            myHandler.sendMessage(msg);
                                        }
                                    }).start();
                                }
                            })
                            .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 点击“返回”后的操作,这里不设置没有任何操作
                                }
                            }).show();
//        		            	ViewInject.toast(myCmdId);
                }

            }
        }
    }

}
